const base_url = 'http://xjj0427.icu/wp-json/wp/v2/pod_yys/'
const Path = '/sdcard/Pictures/' + device.getAndroidId() + '/'  // 目录
const w = device.width  // 设备屏幕分辨率宽度
const h = device.height // 设备屏幕分辨率高度
const tail = '       -------Utils:'

files.ensureDir(Path)

Array.prototype.remove = function (val) {
    var index = this.indexOf(val)
    if (index > -1) {
        this.splice(index, 1)
    }
}


/**
 * @description 初始化
 * @param {Boolean}
 */
const init = (screen_flag) => {
    // if(!requestScreenCapture(screen_flag)){
    //     toast("请求截图失败")
    //     exit()
    // }
    // 修改toast方法
    // var _toast_ = toast
    // toast = message => {
    //   _toast_(message)
    //   sleep(2000)
    // }
}

/**
 * 设置百度Ocr api 、 secret
 */
const set_baiduOrc_key = () => {
    var storge = storages.create('yys')
    storge.put('bd_api_key', 'LGZTmkf9AwP78E01jiYpmDyM')
    storge.put('bd_secret_key', 'WGOi6d3tQvtB2B95XZCe2zeEnL5E1rtO')
}

/**
 * @description 获取百度AI识别token
 * @return {String} 
 */
const get_baidu_access_Token = () => {
    //access_token获取地址,向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求（推荐使用POST），并在URL中带上以下参数：
    //access_token = http.get("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=YIKKfQbdpYRRYtqqTPnZ5bCE&client_secret=hBxFiPhOCn6G9GH0sHoL0kTwfrCtndDj").body.json().access_token;
    // const API_Key = "LGZTmkf9AwP78E01jiYpmDyM"
    // const Secret_Key = "WGOi6d3tQvtB2B95XZCe2zeEnL5E1rtO"
    var storage = storages.create('yys')
    var API_Key = storage.get('bd_api_key')
    var Secret_Key = storage.get('bd_secret_key')
    var post_url = "https://aip.baidubce.com/oauth/2.0/token"
    var token_Res = http.post(post_url, {
        grant_type: "client_credentials",
        client_id: API_Key,
        client_secret: Secret_Key,
    })
    var access_token = token_Res.body.json().access_token
    return access_token
}

/**
 * @description 点击目标字
 * @param {String} word 点击的目标字
 * @param {String} level 识别文字的级别（默认标准位置版）
 * @return {Boolean} 是否点击成功
 */
const clickBaiduWord = (word, level) => {
    var isClick = false
    try {
        shell('screencap -p ' + Path + 'screen.png', true)
    } catch (e) {
        e.javaException instanceof com.stardust.autojs.runtime.exception.ScriptInterruptedException ? captureScreen(Path + 'screen.png') : ''
    }
    var img = images.read(Path + 'screen.png')
    var image = images.toBase64(img, "png", 100)
    var SiteInfo_ocr_Url = level === "high" ? "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate" : "https://aip.baidubce.com/rest/2.0/ocr/v1/general"
    var access_token = get_baidu_access_Token()
    var ocr_Res = http.post(SiteInfo_ocr_Url, {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded" //连接的请求方式,一般是'content-type': 'application/json',
        },
        access_token: access_token,
        image: image,
        recognize_granularity: 'small'
    })
    var json = ocr_Res.body.json().words_result
    for (let w of json) {
        if (w.words.indexOf(word) != -1) {
            let chars = w.chars
            let index = random(0, word.length - 1)
            let word_one = word.substring(index, index + 1)
            for (let item of chars) {
                if (item.char === word_one) {
                    let x = random(item.location.left, item.location.left + item.location.width)
                    let y = random(item.location.top, item.location.top + item.location.height)
                    log(x, y)
                    Tap(x, y)
                    isClick = true
                    break
                }
            }
            break
        }
    }
    return isClick
}

/**
 * @description 获取百度识别源数据
 * @param {String} level 
 * @return {String}
 */
const getBaiduWords = level => {
    try {
        shell('screencap -p ' + Path + 'screen.png', true)
    } catch (e) {
        e.javaException instanceof com.stardust.autojs.runtime.exception.ScriptInterruptedException ? captureScreen(Path + 'screen.png') : ''
    }
    var img = images.read(Path + 'screen.png')
    var image = images.toBase64(img, "png", 100)
    switch (level) {
        case "high_position":
            SiteInfo_ocr_Url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate"
            break
        case "normal_position":
            SiteInfo_ocr_Url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general"
            break
        case "high":
            SiteInfo_ocr_Url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
            break
        default:
            SiteInfo_ocr_Url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
    }
    var access_token = get_baidu_access_Token()
    var ocr_Res = http.post(SiteInfo_ocr_Url, {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        access_token: access_token,
        image: image,
        recognize_granularity: 'small'
    })
    var str = ocr_Res.body.json().words_result || ocr_Res.body
    return str
}

/**
 * @description 百度AI判断是否包含一个目标词
 * @param {String} words 
 * @param {String} level 
 * @return {Boolean}
 */
const isContain = (words, level) => {
    var alive = false
    try {
        shell('screencap -p ' + Path + 'screen.png', true)
    } catch (e) {
        e.javaException instanceof com.stardust.autojs.runtime.exception.ScriptInterruptedException ? captureScreen(Path + 'screen.png') : ''
    }
    var img = images.read(Path + 'screen.png')
    var image = images.toBase64(img, "png", 100)
    var SiteInfo_ocr_Url = level == 'high' ? 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic' : 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'
    var access_token = get_baidu_access_Token()
    var ocr_Res = http.post(SiteInfo_ocr_Url, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        access_token: access_token,
        image: image
    })
    var json = ocr_Res.body.json().words_result
    json == undefined && (log('Upper limit of times'+tail+'isContain'), exit())
    for (let item of json) {
        if (item.words.indexOf(words) != -1) {
            alive = true
            break
        }
    }
    return alive
}

/**
 * @description 百度AI判断是否包含多个目标词
 * @param {Array} words_arr 
 * @param {String} level 
 * @return {Boolean}
 */
const isContains = (words_arr, level) => {
    typeof words_arr == 'object' && words_arr.length > 0 ? '' : (log('Parameter error'), exit())
    var alive = false
    try {
        shell('screencap -p ' + Path + 'screen.png', true)
    } catch (e) {
        e.javaException instanceof com.stardust.autojs.runtime.exception.ScriptInterruptedException ? captureScreen(Path + 'screen.png') : ''
    }
    var img = images.read(Path + 'screen.png')
    var image = images.toBase64(img, "png", 100)
    var SiteInfo_ocr_Url = level == 'high' ? 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic' : 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'
    var access_token = get_baidu_access_Token()
    var ocr_Res = http.post(SiteInfo_ocr_Url, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        access_token: access_token,
        image: image
    })
    var json = ocr_Res.body.json().words_result
    json == undefined && (log('Upper limit of times'+tail+'isContains'), exit())
    for (let word_item of words_arr) {
        for (let item of json) {
            if (item.words.indexOf(word_item) != -1) {
                alive = true
                return alive
            }
        }
    }
    return alive
}

/**
 * @description 获取单个目标字的坐标
 * @param {String} words
 * @param {String} word
 * @param {String} level
 * @return {JSON}
 */
const getWordsPosition = (words, word, level) => {
    var posi = { x: '-1' }
    try {
        shell('screencap -p ' + Path + 'screen.png', true)
    } catch (e) {
        e.javaException instanceof com.stardust.autojs.runtime.exception.ScriptInterruptedException ? captureScreen(Path + 'screen.png') : ''
    }
    var img = images.read(Path + 'screen.png')
    var image = images.toBase64(img, "png", 100)
    var SiteInfo_ocr_Url = level === "high" ? "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate" : "https://aip.baidubce.com/rest/2.0/ocr/v1/general"
    var access_token = get_baidu_access_Token()
    var ocr_Res = http.post(SiteInfo_ocr_Url, {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded" //连接的请求方式,一般是'content-type': 'application/json',
        },
        access_token: access_token,
        image: image,
        recognize_granularity: 'small'
    })
    var json = ocr_Res.body.json().words_result
    json == undefined && (log('Upper limit of times'+tail+'getWordsPosition'), exit())
    for (let w of json) {
        if (w.words.indexOf(words) != -1) {
            let chars = w.chars
            for (let item of chars) {
                if (item.char == word) {
                    let x = random(item.location.left, item.location.left + item.location.width)
                    let y = random(item.location.top, item.location.top + item.location.height)
                    posi = { x: x, y: y }
                    break
                }
            }
            break
        }
    }
    return posi
}

/**
 * @description 获取单个目标字的所有坐标
 * @param {String} words
 * @param {String} level
 * @return {JSON}
 */
const getWordsAllPosition = (words, level) => {
    var posi_arr = [], posi = {}
    try {
        shell('screencap -p ' + Path + 'screen.png', true)
    } catch (e) {
        e.javaException instanceof com.stardust.autojs.runtime.exception.ScriptInterruptedException ? captureScreen(Path + 'screen.png') : ''
    }
    var img = images.read(Path + 'screen.png')
    var image = images.toBase64(img, "png", 100)
    var SiteInfo_ocr_Url = level === "high" ? "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate" : "https://aip.baidubce.com/rest/2.0/ocr/v1/general"
    var access_token = get_baidu_access_Token()
    var ocr_Res = http.post(SiteInfo_ocr_Url, {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded" //连接的请求方式,一般是'content-type': 'application/json',
        },
        access_token: access_token,
        image: image,
        recognize_granularity: 'small'
    })
    var json = ocr_Res.body.json().words_result
    json == undefined && (log('Upper limit of times'+tail+'getWordsAllPosition'), exit())
    let index = random(0, words.length - 1)
    let one_word = words.substring(index, index + 1)
    json.forEach(w => {
        if (w.words.indexOf(words) != -1) {
            let chars = w.chars
            for (let item of chars) {
                if (item.char == one_word) {
                    let x = random(item.location.left, item.location.left + item.location.width)
                    let y = random(item.location.top, item.location.top + item.location.height)
                    posi = { x: x, y: y }
                    break
                }
            }
            posi_arr.push(posi)
        }
    })
    return posi_arr
}

/**
 * @description 获取所有目标字的坐标
 * @param {Array} wordArray
 * @param {String} level
 * @return {Array}
 */
const getAllPosition = (wordArray, level) => {
    var posi = { x: -1, y: -1, w: -1, h: -1 }, posi_arr = []
    try {
        shell('screencap -p ' + Path + 'screen.png', true)
    } catch (e) {
        e.javaException instanceof com.stardust.autojs.runtime.exception.ScriptInterruptedException ? captureScreen(Path + 'screen.png') : ''
    }
    var img = images.read(Path + 'screen.png')
    var image = images.toBase64(img, "png", 100)
    var SiteInfo_ocr_Url = level === "high" ? "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate" : "https://aip.baidubce.com/rest/2.0/ocr/v1/general"
    var access_token = get_baidu_access_Token()
    var ocr_Res = http.post(SiteInfo_ocr_Url, {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded" //连接的请求方式,一般是'content-type': 'application/json',
        },
        access_token: access_token,
        image: image,
        recognize_granularity: 'small'
    })
    var json = ocr_Res.body.json().words_result
    json == undefined && (log('Upper limit of times'+tail+'getAllPosition'), exit())
    let temp_arr = []
    for (let itemObj of wordArray) {      // 遍历每一个词组
        let temp = true
        json.forEach(w => {
            if (w.words.indexOf(itemObj) != -1) {   // 是否包含词组
                temp = false
                let chars = w.chars
                for (let i = 0; i < itemObj.length; i++) {
                    let word = itemObj.substring(i, i + 1)
                    for (let item of chars) {
                        if (item.char == word) {
                            let x = item.location.left
                            let y = item.location.top
                            let w = item.location.width
                            let h = item.location.height
                            posi = { x: x, y: y, w: w, h: h }
                            break
                        }
                    }
                    temp_arr.push(posi)
                    posi = { x: -1, y: -1, w: -1, h: -1 }
                }
            }
        })
        if (temp) {
            posi = { x: -1, y: -1, w: -1, h: -1 }
            for (let i = 0; i < itemObj.length; i++) {
                temp_arr.push(posi)
            }
        }
        posi_arr.push(temp_arr)
        temp_arr = []
    }
    return posi_arr
}

/**
 * @description 获取本地文件JSON
 * @param {String} path 文件路径
 * @return {JSON}
 */
const getPathJson = path => {
    var jsonObj
    if (files.exists(path)) {
        let texts = files.read(path)
        try {
            texts != '' ? jsonObj = JSON.parse(texts) : ''
        } catch (e) {
            jsonObj = undefined
        }
    } else {
        log('文件不存在！')
    }
    return jsonObj
}

/**
 * @description 保存JSON到文件
 * @param {String} path 
 * @param {JSON} json 
 * @return {Boolean} 
 */
const savePathJson = (path, json) => {
    let isSave = false
    if (files.ensureDir(path)) {
        let jsonStr = JSON.stringify(json)
        files.write(path, jsonStr)
        isSave = true
    }
    return isSave
}

/**
 * @description 滑动
 * @param {String} dire 
 * @return {Booleann}
 */
const swipeTo = dire => {
    let isSwipe = false
    switch (dire) {
        case 'ba':
            isSwipe = Swipe(random(1, w - 1), random(h - 10, h - 1), random(1, w - 1), random(1, 10), random(700, 800))
            break
        case 'top':
            isSwipe = Swipe(random(w / 9 * 2, w / 9 * 7), random(h / 11 * 9, h / 11 * 10), random(w / 9 * 2, w / 9 * 7), random(h / 11 * 2, h / 11 * 3), random(400, 500))
            break
        case 'bottom':
            isSwipe = Swipe(random(w / 9 * 2, w / 9 * 7), random(h / 11 * 2, h / 11 * 3), random(w / 9 * 2, w / 9 * 7), random(h / 11 * 9, h / 11 * 10), random(400, 500))
            break
        case 'left':
            isSwipe = Swipe(random(w / 11 * 9, w / 11 * 10), random(h / 7 * 2, h / 7 * 5), random(w / 11, w / 11 * 2), random(h / 7 * 2, h / 7 * 5), random(500, 600))
            break
        default:
            isSwipe = Swipe(random(w / 11, w / 11 * 2), random(h / 7 * 2, h / 7 * 5), random(w / 11 * 9, w / 11 * 10), random(h / 7 * 2, h / 7 * 5), random(500, 600))
    }
    return isSwipe
}

/**
 * @description 平滑滑动
 * @param {String} dire 
 * @return {Booleann}
 */
const SwipeTo = dire => {
    let isSwipe = false
    switch (dire) {
        case 'top':
            isSwipe = Swipe(random(1, w - 1), random(h / 11 * 9, h / 11 * 10), random(1, w - 1), random(h / 10, h / 10 * 2), random(100, 200))
            break
        default:
            isSwipe = Swipe(random(1, w - 1), random(h / 10, h / 10 * 2), random(1, w - 1), random(h / 11 * 10, h - 1), random(100, 200))
    }
    return isSwipe
}

/**
 * @description 向上滑动(贴吧刷贴专用)
 */
const baSwipeUp = () => {
    let isSwipe = false
    isSwipe = Swipe(random(w / 9 * 2, w / 9 * 7), random(h / 11 * 9, h / 11 * 10), random(w / 9 * 2, w / 9 * 7), random(1, 10), random(400, 500))
    return isSwipe
}

/**
 * @description 贴子中随意上下滑动
 * @param {String} dire 
 * @returns {Boolean}
 */
const tieBaRanSwipe = dire => {
    let isSwipe = false
    isSwipe = dire == 'down' ? Swipe(random(w / 10, w / 10 * 9), random(0.17 * h, 0.2 * h), random(w / 10, w / 10 * 9), random(h / 10 * 9, h / 10 * 8), random(50, 300)) : Swipe(random(w / 10, w / 10 * 9), random(h / 10 * 9, h / 10 * 8), random(w / 10, w / 10 * 9), random(0.17 * h, 0.2 * h), random(150, 300))
}

/**
 * @description 截取字符串中随机的一个字符
 * @param {String} str 
 * @return {String} 
 */
const getRanWord = str => {
    if (str.length > 0) {
        let num = random(1, str.length)
        let word = str.substring(num - 1, num)
        return word
    } else {
        log('字符为空')
    }
}

/**
 * @description 获取文本文件随机行字符
 * @param {String} path 
 */
const getWaterWords = path => {
    if (files.exists(path)) {
        let textObj = open(path)
        let textArr = textObj.readlines()
        return textArr[random(0, textArr.length - 1)]
    } else {
        log('文本不存在！')
        exit()
    }
}

/**
 * @description 检测应用是否未响应
 * @param {String} path
 */
const testAppResp = path => {
    threads.start(function () {
        while (true) {
            let UIObj = text('关闭应用').findOnce()
            if (UIObj != null) {
                log('应用无响应，关闭应用')
                UIObj.tap()
                sleep(5000)
                launch(path)
            }
            sleep(15000)
        }
    })
}

/**
 * @description Get请求
 * @param {*} url 
 */
// const getRequest = url => {
//     return new Promise((resolve,reject)=>{
//         let data = http.get(url)
//         data.statusCode===200? resolve(data.body.json()):reject(data.body.json())
//     })
// }
const getRequest = url => {
    return http.get(url,{
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
        }
    })
}

/**
 * @description Post请求
 * @param {*} url 
 * @param {*} data 
 */
const postRequest = (url, data) => {
    return http.post(url, data)
}

/**
 * @description 比较两个日期的大小
 * @param {*} dateone 
 * @param {*} datetwo 
 */
const compare = (dateone, datetwo) => {
    let flag = dateone > datetwo ? true : false
    return flag
}

/**
 * @description 将字符串数组转化成单字符串数组
 * @param {*} arr 
 */
function strArrToStrArr(arr) {
    let arr_new = []
    if (arr.length > 0) for (let item of arr) for (let i = 0; i < item.length; i++) arr_new.push(item.substring(i, i + 1))
    return arr_new
}

/**
 * @description 验证密钥是否过期
 * @param {*} pwd 密钥
 */
const isAlive = pwd => {
    let falg = false
    let id = uncompileStr(pwd)
    let request = getRequest(base_url + id)
    if (request.statusCode === 200) {
        let data = JSON.parse(request.body.string())
        let pod_due_date = data.pod_due_date
        let dateone = new Date(Date.parse(pod_due_date.replace(/-/g, '/')))
        falg = compare(dateone, new Date())
    }
    return falg
}

/**
 * @description 等待
 */
const sleeps = () => {
    sleep(random(3000, 5000))
}

/**
 * @description 等待计时并报时
 * @param {Number} second 
 */
const waitTime = second => {
    log('需等待 ' + second + ' 秒')
    for (let i = 1; i <= second; i++) sleep(1000), log('已等待：' + i + '秒')
}

/**
 * @description 随机等待计时并报时
 * @param {Number} first 
 * @param {Number} second 
 */
const ranWaitTime = (first, second) => {
    let times = random(first, second)
    log('需等待 ' + times + ' 秒')
    for (let i = 1; i <= times; i++) sleep(1000), log('已等待：' + i + '秒')
}

/**
 * @description 运行的时间
 * @param {Number} times 
 */
const runTime = times => {
    threads.start(function () {
        log('运行时间：' + times + ' 分钟')
        for (let i = 1; i <= times; i++) {
            sleep(60 * 1000)
            log('已运行 ' + i + ' 分钟')
        }
        exit()
    })
}

/**
 * @description 对字符串进行(硬核)加密
 * @param {*} code 
 */
const compileStr = code => {
    return ((code * 427 - 10) * 328 - 10) * 328 - 1
}

/**
 * @description 对字符串进行(硬核)解密
 * @param {*} code 
 */
const uncompileStr = code => {
    return (((Number(code) + 1) / 328 + 10) / 328 + 10) / 427
}

/**
 * @description 停止当前脚本的运行
 */
const stopJB = () => {
    setTimeout(() => {
        engines.myEngine().forceStop()
    }, 3000)
}

module.exports = {
    Path: Path,                                  // 目录
    init: init,                                  // 初始化
    stopJB: stopJB,                              // 停止当前脚本的运行
    compileStr: compileStr,                      // 对字符串进行(硬核)加密
    uncompileStr: uncompileStr,                  // 对字符串进行(硬核)解密
    getRequest: getRequest,                      // Get请求
    postRequest: postRequest,
    compare: compare,
    isAlive: isAlive,
    runTime: runTime,                            // 运行的时间
    sleeps: sleeps,                              // 等待
    waitTime: waitTime,                          // 等待计时并报时
    ranWaitTime: ranWaitTime,                    // 随机等待计时并报时
    strArrToStrArr: strArrToStrArr,
    set_baiduOrc_key: set_baiduOrc_key,          // 设置百度Ocr api 、 secret
    getWordsAllPosition: getWordsAllPosition,    // 获取单个目标字的所有坐标
    getAllPosition: getAllPosition,              // 获取所有目标字的坐标
    getBaiduWords: getBaiduWords,                // 获取百度识别源数据
    clickBaiduWord: clickBaiduWord,
    getPathJson: getPathJson,                    // 获取本地文件JSON
    savePathJson: savePathJson,
    getWordsPosition: getWordsPosition,
    isContain: isContain,                        // 判断是否包含一个目标词
    isContains: isContains,                      // 判断是否包含多个目标词
    swipeTo: swipeTo,
    SwipeTo: SwipeTo,
    getRanWord: getRanWord,
    getWaterWords: getWaterWords,
    testAppResp: testAppResp,
    baSwipeUp: baSwipeUp,
    tieBaRanSwipe: tieBaRanSwipe,
}
